package com.example.meitao.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.example.meitao.R;
import com.example.meitao.adapter.CommunityListAdapter;
import com.example.meitao.bean.CommunityBean;
import com.example.meitao.config.NetConfig;
import com.google.gson.Gson;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 琚雷 on 2016-9-2.
 */
public class StudyFragment extends Fragment {
    private RecyclerView rv_study_show;
    private CommunityListAdapter mCommunityListAdapter;
    private List<CommunityBean.DataBean.ResultsBean> mData;
    private LinearLayoutManager layoutManager;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view =LayoutInflater.from(getActivity()).inflate(R.layout.fragment_study,null);
        initView(view);
        initData();
        setData();
        return view;
    }

    private void setData() {
        layoutManager=new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false);
        rv_study_show.setLayoutManager(layoutManager);
        rv_study_show.setAdapter(mCommunityListAdapter);
    }
    private void initData() {
        RequestParams params = new RequestParams(NetConfig.COMMUNITY_PATH);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                CommunityBean communityBean = gson.fromJson(result, CommunityBean.class);
                mData.addAll(communityBean.getData().getResults());
                mCommunityListAdapter.notifyDataSetChanged();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(getActivity(), "网络连接异常，请检查网络连接！", Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void initView(View view) {
        rv_study_show = (RecyclerView) view.findViewById(R.id.rv_study_show);
        mData = new ArrayList<>();
        mCommunityListAdapter = new CommunityListAdapter(getActivity(), mData);
    }
}